﻿using CP.Entities;
using CP.Utility;
using DevExpress.XtraTreeList.Nodes;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CP.Controllers.GPM;
using DevExpress.XtraTreeList;

namespace GPM
{
    public partial class FrmFormAuth : BaseForm
    {
        GridCheckMarksSelection selection;
        public int CurrentGroupID { get; private set; }
        public string CurrentGroupName { get; private set; }
        FormAuthController fController = new FormAuthController();

        public FrmFormAuth()
        {
            InitializeComponent();
            this.BarComponents = components;
            InitializeTreeView();
        }

        private void InitializeTreeView()
        {
            DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn1 = new DevExpress.XtraTreeList.Columns.TreeListColumn();
            DevExpress.XtraTreeList.Columns.TreeListColumn treeColMenu = new DevExpress.XtraTreeList.Columns.TreeListColumn();
            DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn2 = new DevExpress.XtraTreeList.Columns.TreeListColumn();

            treeListColumn1.Caption = "主键";
            treeListColumn1.FieldName = "webpart_id";
            treeListColumn1.Name = "treeListColumn1";
            treeListColumn1.Visible = false;

            treeListColumn2.Caption = "窗体ID";
            treeListColumn2.FieldName = "form_name";
            treeListColumn2.Name = "treeListColumn2";
            treeListColumn2.Visible = false;

            treeColMenu.Caption = "窗体中文名";
            treeColMenu.FieldName = "form_text";
            treeColMenu.MinWidth = 49;
            treeColMenu.Name = "treeColMenu";
            treeColMenu.OptionsColumn.AllowEdit = false;
            treeColMenu.OptionsColumn.AllowMove = false;
            treeColMenu.OptionsColumn.AllowMoveToCustomizationForm = false;
            treeColMenu.OptionsColumn.ReadOnly = true;
            treeColMenu.OptionsColumn.ShowInCustomizationForm = false;
            treeColMenu.RowFooterSummaryStrFormat = "";
            treeColMenu.SummaryFooter = DevExpress.XtraTreeList.SummaryItemType.Count;
            treeColMenu.SummaryFooterStrFormat = "未授权数：{0}";
            treeColMenu.Visible = true;
            treeColMenu.VisibleIndex = 0;
            treeUnAuth.treeView.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] {
            treeListColumn1,
            treeListColumn2,
            treeColMenu});

            DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn1Au = new DevExpress.XtraTreeList.Columns.TreeListColumn();
            DevExpress.XtraTreeList.Columns.TreeListColumn treeColMenuAu = new DevExpress.XtraTreeList.Columns.TreeListColumn();
            DevExpress.XtraTreeList.Columns.TreeListColumn treeListColumn3 = new DevExpress.XtraTreeList.Columns.TreeListColumn();

            treeListColumn3.Caption = "窗体ID";
            treeListColumn3.FieldName = "form_name";
            treeListColumn3.Name = "treeListColumn3";
            treeListColumn3.Visible = false;

            treeListColumn1Au.Caption = "主键";
            treeListColumn1Au.FieldName = "webpart_id";
            treeListColumn1Au.Name = "treeListColumn1Au";

            treeColMenuAu.Caption = "窗体中文名";
            treeColMenuAu.FieldName = "form_text";
            treeColMenuAu.MinWidth = 49;
            treeColMenuAu.Name = "treeColMenuAu";
            treeColMenuAu.OptionsColumn.AllowEdit = false;
            treeColMenuAu.OptionsColumn.AllowMove = false;
            treeColMenuAu.OptionsColumn.ReadOnly = true;
            treeColMenuAu.SummaryFooter = DevExpress.XtraTreeList.SummaryItemType.Count;
            treeColMenuAu.SummaryFooterStrFormat = "授权数：{0}";
            treeColMenuAu.Visible = true;
            treeColMenuAu.VisibleIndex = 0;
            treeColMenuAu.OptionsColumn.AllowSize = true;
            treeAuth.treeView.Columns.AddRange(new DevExpress.XtraTreeList.Columns.TreeListColumn[] {
            treeListColumn1Au,
            treeListColumn3,
            treeColMenuAu});
        }

        private void FrmFormAuth_Load(object sender, EventArgs e)
        {
            selection = new GridCheckMarksSelection(gvUserGroup);
            this.treeUnAuth.Refresh_ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(treeUnAuth_Refresh_ItemClick);
            this.treeAuth.Refresh_ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(treeAuth_Refresh_ItemClick);
            this.treeAuth.treeView.DoubleClick += new EventHandler(treeView_DoubleClick);
            this.gcUserGroup.DataSource = fController.GetUserGroups();
        }

        void treeView_DoubleClick(object sender, EventArgs e)
        {
            TreeListNode node = treeAuth.treeView.FocusedNode;
            if (node.Tag == null) return;

            int webpartid = Convert.ToInt32(node.Tag);
            string formtext = node.GetValue(treeAuth.treeView.Columns["form_text"]).ToString();

            FrmButtonAuthorize frm = new FrmButtonAuthorize(CurrentGroupID, CurrentGroupName, formtext, webpartid);
            frm.ShowDialog();
        }

        void treeAuth_Refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //User_Group group = bsUserGroup.Current as User_Group;
            //if (null == group)
            //{
            //    ExMessageBox.Show("提示信息：没有选中角色！");
            //    return;
            //}
            //BindingAuthForms(group.group_id);
        }

        void treeUnAuth_Refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //User_Group group = bsUserGroup.Current as User_Group;
            //if (null == group)
            //{
            //    ExMessageBox.Show("提示信息：没有选中角色！");
            //    return;
            //}
            //BindingUnAuthForms(group.group_id);
        }

        private void gvUserGroup_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            User_Group group = gvUserGroup.GetFocusedRow() as User_Group;
            if (null == group)
                return;
            this.CurrentGroupID = group.group_id;
            this.CurrentGroupName = group.group_name;
            BindingFormTree(group.group_id);
        }

        private void BindingAuthForms(int groupid)
        {
            var modules = fController.GetAuthModules(groupid);
            var forms = fController.GetAuthedForms(groupid);
            AppendNodes(this.treeAuth.treeView, modules, forms);
        }

        private void BindingUnAuthForms(int groupid)
        {
            var modules = fController.GetUnAuthModules(groupid);
            var forms = fController.GetUnAuthedForms(groupid);
            AppendNodes(this.treeUnAuth.treeView, modules, forms);
        }

        private void AppendNodes(TreeList treeview, IList<Module> modules, IList<Webpart> forms)
        {
            Cursor currentCursor = Cursor.Current;
            Cursor.Current = Cursors.WaitCursor;

            treeview.BeginUpdate();
            treeview.Nodes.Clear();

            foreach (Module module in modules)
            {
                TreeListNode root = treeview.AppendNode((new object[] { module.module_id, module.module_id, module.module_name }), -1, -1, -1, 3);
                foreach (Webpart webpart in forms.Where(f => f.module_id == module.module_id))
                {
                    TreeListNode child = treeview.AppendNode(new object[] { webpart.webpart_id, webpart.form_name, webpart.form_text }, root.Id, -1, -1, 2);
                    child.Tag = webpart.webpart_id;
                }
            }

            if (treeview.Nodes.Count > 0)
                treeview.Nodes[0].ExpandAll();
            treeview.EndUpdate();

            Cursor.Current = currentCursor;
        }

        private void btnAuth_Click(object sender, EventArgs e)
        {
            if (this.CurrentGroupID == 0)
            {
                ExMessageBox.Show("提示：没有选中角色！", AppSetter.SoftName);
                return;
            }

            IList<int> nodes = new List<int>();
            GetCheckedIndeterminateNodes(treeUnAuth.treeView.Nodes, nodes);
            if (0 == nodes.Count)
            {
                ExMessageBox.Show("提示：没有选中未授权的窗体！");
                return;
            }

            try
            {
                //SplashScreenManager.ShowForm(typeof(WaitForm1));
                splashScreenManager1.ShowWaitForm();
                fController.FormAuth(this.CurrentGroupID, nodes);
                LogHelper.Log("窗体授权", "insert", "授权", "group_id:" + this.CurrentGroupID, "nodes:" + string.Join(",", nodes));
                ExMessageBox.Show("提示：窗体授权成功！");
                BindingFormTree(this.CurrentGroupID);
            }
            catch (Exception ex)
            {
                ExMessageBox.Show(ex.Message);
            }
            //SplashScreenManager.CloseForm();
            splashScreenManager1.CloseWaitForm();
        }

        private void BindingFormTree(int group_id)
        {
            BindingAuthForms(group_id);
            BindingUnAuthForms(group_id);
        }

        private void btnCancelAuth_Click(object sender, EventArgs e)
        {
            if (this.CurrentGroupID == 0)
            {
                ExMessageBox.Show("提示：没有选中角色！", AppSetter.SoftName);
                return;
            }

            IList<int> nodes = new List<int>();
            GetCheckedIndeterminateNodes(treeAuth.treeView.Nodes, nodes);
            if (0 == nodes.Count)
            {
                ExMessageBox.Show("提示：没有选中已授权的窗体！");
                return;
            }

            try
            {
                //SplashScreenManager.ShowForm(typeof(WaitForm1));
                splashScreenManager1.ShowWaitForm();
                fController.FormUnAuth(this.CurrentGroupID, nodes);
                LogHelper.Log("窗体授权", "delete", "取消授权", "group_id:" + this.CurrentGroupID, "nodes:" + string.Join(",", nodes));
                ExMessageBox.Show("提示：窗体取消授权成功！");
                BindingFormTree(this.CurrentGroupID);
            }
            catch (Exception ex)
            {
                ExMessageBox.Show(ex.Message);
            }
            //SplashScreenManager.CloseForm();
            splashScreenManager1.CloseWaitForm();
        }

        private void GetCheckedIndeterminateNodes(TreeListNodes nodes, IList<int> checkednodes)
        {
            foreach (TreeListNode parent in nodes)
            {
                if ((parent.CheckState == CheckState.Checked) ||
                    (parent.CheckState == CheckState.Indeterminate))
                {
                    foreach (TreeListNode child in parent.Nodes)
                    {
                        if (child.CheckState == CheckState.Checked)
                            checkednodes.Add(child.Tag == null ? -1 : Convert.ToInt32(child.Tag));
                    }
                }
            }
        }

        private void btnColList_Click(object sender, EventArgs e)
        {
            TreeListNode node = treeAuth.treeView.FocusedNode;
            if (node.Tag == null)
                return;

            int webpartid = Convert.ToInt32(node.Tag);
            string formtext = node.GetValue(treeAuth.treeView.Columns["form_text"]).ToString();

            FrmColListAuthorize frm = new FrmColListAuthorize(CurrentGroupID, CurrentGroupName, formtext, webpartid);
            frm.ShowDialog();
        }
    }
}
